import { request } from '@/utils/request'
import type { CustomAxiosRequestConfig } from '@/utils/request'
import type { TaskCreateForm, TaskUpdateForm, TaskFilter } from '@/types/task'
import type { ApiResponse } from '@/types/api'

// 任务类型定义（从 task.ts 迁移）
export interface Task {
  id: string
  title: string
  description?: string
  task_type: string
  status: string
  priority: string
  assignee_id?: string
  reporter_id?: string
  project_id: string
  requirement_id?: string
  requirement_name?: string
  estimated_hours?: number
  actual_hours?: number
  start_date?: string
  due_date?: string
  tags?: string[]
  dependencies?: string[]
  organization_id?: string
  comments?: any[]
  attachments?: any[]
  time_logs?: any[]
  created_by?: string
  created_at: string
  updated_at: string
  comment_count?: number
  attachment_count?: number
  total_time_spent?: number
}

export interface TaskQueryParams {
  page?: number
  size?: number
  project_id?: string
  status?: string
  assignee_id?: string
  search?: string
  version_id?: string
  requirement_id?: string
}

// 扩展TaskQueryParams以包含TaskFilter的所有字段
interface ExtendedTaskQueryParams extends TaskFilter, TaskQueryParams {
  size?: number  // 每页记录数（兼容前端参数）
  sort_by?: string
  sort_order?: 'asc' | 'desc'
}

/**
 * 处理API响应，统一转换为ApiResponse格式
 */
function handleApiResponse<T>(response: any, defaultData: T): ApiResponse<T> {
  if (response.data && response.data.success) {
    return {
      status: response.status,
      statusText: response.statusText,
      success: response.data.success,
      code: response.data.code,
      message: response.data.message,
      data: response.data.data || defaultData,
      pagination: response.data.pagination,
      timestamp: new Date().toISOString()
    }
  }
  // 确保始终返回ApiResponse格式
  return {
    status: response.status || 500,
    statusText: response.statusText || 'Internal Server Error',
    success: false,
    code: response.data?.code || 500,
    message: response.data?.message || '请求失败',
    data: defaultData,
    timestamp: new Date().toISOString()
  }
}

export const getTasks = (params?: ExtendedTaskQueryParams) => {
  // 转换参数：处理空字符串和undefined
  const requestParams: any = {}
  if (params) {
    // 分页参数：优先使用page/size
    if (params.page !== undefined && params.page !== null) {
      requestParams.page = params.page
    }
    if ((params as any).size !== undefined && (params as any).size !== null) {
      requestParams.size = (params as any).size
    } else if (params.limit !== undefined && params.limit !== null) {
      requestParams.limit = params.limit
    }
    
    // 搜索关键词
    if (params.search !== undefined && params.search !== null && params.search !== '') {
      requestParams.search = params.search.trim()
    }
    
    // 项目筛选
    if (params.project_id !== undefined && params.project_id !== null && params.project_id !== '') {
      requestParams.project_id = params.project_id
    }
    
    // 版本筛选
    if (params.version_id !== undefined && params.version_id !== null && params.version_id !== '') {
      requestParams.version_id = params.version_id
    }
    
    // 负责人筛选
    if (params.assignee_id !== undefined && params.assignee_id !== null && params.assignee_id !== '') {
      requestParams.assignee_id = params.assignee_id
    }
    
    // 报告人筛选
    if (params.reporter_id !== undefined && params.reporter_id !== null && params.reporter_id !== '') {
      requestParams.reporter_id = params.reporter_id
    }
    
    // 状态筛选
    if (params.status !== undefined && params.status !== null && params.status !== '') {
      requestParams.status = params.status
    }
    
    // 优先级筛选
    if (params.priority !== undefined && params.priority !== null) {
      requestParams.priority = params.priority
    }
    
    // 任务类型筛选
    if (params.task_type !== undefined && params.task_type !== null) {
      requestParams.task_type = params.task_type
    }
    
    // 日期范围筛选
    if (params.due_date_from !== undefined && params.due_date_from !== null && params.due_date_from !== '') {
      requestParams.due_date_from = params.due_date_from
    }
    if (params.due_date_to !== undefined && params.due_date_to !== null && params.due_date_to !== '') {
      requestParams.due_date_to = params.due_date_to
    }
    
    // 标签筛选
    if (params.tags && Array.isArray(params.tags) && params.tags.length > 0) {
      requestParams.tags = params.tags.join(',')
    }
    
    // 排序
    if (params.sort_by !== undefined && params.sort_by !== null && params.sort_by !== '') {
      requestParams.sort_by = params.sort_by
    }
    if (params.sort_order !== undefined && params.sort_order !== null) {
      requestParams.sort_order = params.sort_order
    }
  }
  
  return request.get('/tasks/', { params: requestParams })
}

export const getTasksCount = (params?: TaskFilter) => {
  return request.get('/tasks/count', { params })
}

export const getTask = (id: string) => {
  return request.get(`/tasks/${id}`)
}

export const createTask = (data: TaskCreateForm) => {
  return request.post('/tasks/', data)
}

export const updateTask = (id: string, data: TaskUpdateForm) => {
  return request.put(`/tasks/${id}`, data).then(response => {
    // 处理响应，确保返回统一的格式
    if (response.data && response.data.success) {
      return {
        ...response,
        data: response.data
      }
    }
    return response
  })
}

export const deleteTask = (id: string) => {
  return request.delete(`/tasks/${id}`).then(response => {
    if (response.data && response.data.success === false) {
      throw new Error(response.data.message || '删除任务失败')
    }
    return response
  })
}

export const batchDeleteTasks = (ids: string[]) => {
  return request.delete('/tasks/batch', { params: { ids } }).then(response => {
    if (response.data && response.data.success === false) {
      throw new Error(response.data.message || '批量删除任务失败')
    }
    return response
  })
}

export const updateTaskStatus = (id: string, status: string) => {
  // 验证参数
  if (!id || id.trim() === '') {
    return Promise.reject(new Error('任务ID无效'))
  }
  if (!status || status.trim() === '') {
    return Promise.reject(new Error('任务状态无效'))
  }
  
  const config: CustomAxiosRequestConfig = {
    showError: true,
    showSuccess: false // 由调用方控制成功提示
  }
  return request.patch(`/tasks/${id}/status`, { status }, config)
    .then(response => handleApiResponse(response, {} as any))
    .catch(error => {
      console.error('更新任务状态失败:', error)
      // 处理404错误
      if (error?.response?.status === 404) {
        throw new Error('任务不存在或已被删除')
      }
      // 处理权限错误
      if (error?.response?.status === 403) {
        throw new Error('您没有权限更新此任务状态')
      }
      throw error
    })
}

export const updateTaskProgress = (id: string, progress: number) => {
  return request.patch(`/tasks/${id}/progress`, { progress }).then(response => 
    handleApiResponse(response, {} as any)
  )
}

export const assignTask = (id: string, assignee_id: string) => {
  return request.patch(`/tasks/${id}/assignee`, { assignee_id })
}

export const updateTaskPriority = (id: string, priority: string) => {
  // 验证参数
  if (!id || id.trim() === '') {
    return Promise.reject(new Error('任务ID无效'))
  }
  if (!priority || priority.trim() === '') {
    return Promise.reject(new Error('任务优先级无效'))
  }
  
  const config: CustomAxiosRequestConfig = {
    showError: true,
    showSuccess: false // 由调用方控制成功提示
  }
  return request.put(`/tasks/${id}`, { priority }, config)
    .then(response => handleApiResponse(response, {} as any))
    .catch(error => {
      console.error('更新任务优先级失败:', error)
      // 处理404错误
      if (error?.response?.status === 404) {
        throw new Error('任务不存在或已被删除')
      }
      // 处理权限错误
      if (error?.response?.status === 403) {
        throw new Error('您没有权限更新此任务优先级')
      }
      throw error
    })
}

export const getTaskComments = (id: string, page: number = 1, pageSize: number = 20) => {
  return request.get(`/tasks/${id}/comments`, {
    params: {
      page,
      page_size: pageSize
    }
  }).then(response => 
    handleApiResponse(response, [] as any[])
  )
}

export const addTaskComment = (id: string, content: string, parent_comment_id?: string) => {
  return request.post(`/tasks/${id}/comments`, { content, parent_comment_id }).then(response => 
    handleApiResponse(response, null as any)
  )
}

export const updateTaskComment = (taskId: string, commentId: string, data: { content?: string; is_deleted?: boolean }) => {
  return request.put(`/tasks/${taskId}/comments/${commentId}`, data).then(response => 
    handleApiResponse(response, null as any)
  )
}

export const revokeTaskComment = (taskId: string, commentId: string) => {
  return updateTaskComment(taskId, commentId, { is_deleted: true })
}

export const deleteTaskComment = (taskId: string, commentId: string) => {
  return request.delete(`/tasks/${taskId}/comments/${commentId}`).then(response => {
    if (response.data && response.data.success === false) {
      throw new Error(response.data.message || '删除评论失败')
    }
    return handleApiResponse(response, null as any)
  })
}

export const getTaskAttachments = (taskId: string) => {
  return request.get(`/tasks/${taskId}/attachments`).then(response => 
    handleApiResponse(response, [] as any[])
  )
}

export const uploadTaskAttachment = (taskId: string, file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  return request.post(`/tasks/${taskId}/attachments`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => 
    handleApiResponse(response, null as any)
  )
}

export const deleteTaskAttachment = (taskId: string, attachmentId: string) => {
  return request.delete(`/tasks/${taskId}/attachments/${attachmentId}`).then(response => {
    if (response.data && response.data.success === false) {
      throw new Error(response.data.message || '删除附件失败')
    }
    return handleApiResponse(response, null as any)
  })
}

export const downloadTaskAttachment = (taskId: string, attachmentId: string) => {
  return request.get(`/tasks/${taskId}/attachments/${attachmentId}/download`, {
    responseType: 'blob'
  })
}

export const exportTasks = (params?: TaskFilter) => {
  return request.get('/tasks/export', {
    params,
    responseType: 'blob'
  })
}

export const importTasks = (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  return request.post('/tasks/import', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export const downloadImportTemplate = () => {
  return request.get('/tasks/import/template', {
    responseType: 'blob'
  })
}

export const getTaskStatistics = (params?: { project_id?: string; start_date?: string; end_date?: string }) => {
  return request.get('/tasks/stats/overview', { params })
}

// 向后兼容：getTaskStats 是 getTaskStatistics 的别名
export const getTaskStats = getTaskStatistics

export const getTaskTimeLogs = (taskId: string, page: number = 1, pageSize: number = 20) => {
  return request.get(`/tasks/${taskId}/time-logs`, {
    params: {
      page,
      page_size: pageSize
    }
  })
}

export const addTaskTimeLog = (taskId: string, data: { duration?: number; hours?: number; date?: string; description?: string }) => {
  // 兼容 duration 和 hours 参数，优先使用 hours
  const requestData = {
    hours: data.hours || data.duration,
    date: data.date,
    description: data.description
  }
  return request.post(`/tasks/${taskId}/time-logs`, requestData)
}

export const deleteTaskTimeLog = (taskId: string, timeLogId: string) => {
  return request.delete(`/tasks/${taskId}/time-logs/${timeLogId}`)
}

export const batchUpdateTasks = (ids: string[], data: { status?: string; assignee_id?: string; priority?: string }) => {
  return request.put('/tasks/batch', { ids, ...data })
}

// 从 task.ts 迁移的函数和对象
/**
 * 获取任务列表（兼容旧版本）
 */
export function getTaskList(params?: TaskQueryParams): Promise<{
  items: Task[]
  total: number
  page: number
  size: number
}> {
  return request({
    url: '/tasks/',
    method: 'get',
    params
  }).then(response => {
    // 处理后端统一响应格式
    // 后端paginated_response返回格式：{success: true, data: [...], pagination: {...}}
    if (response.data && response.data.success) {
      const data = response.data.data
      const pagination = response.data.pagination // pagination在响应数据的顶级
      
      // 情况1: data是数组，pagination是顶级字段（后端paginated_response的标准格式）
      if (Array.isArray(data) && pagination) {
        return {
          items: data.map((task: any) => ({
            ...task,
            id: task.id || task._id,
            assignee_name: task.assignee_name || task.assignee?.name,
            project_name: task.project_name || task.project?.name
          })),
          total: pagination.total || 0,
          page: pagination.page || 1,
          size: pagination.size || (params?.size || 20)
        }
      }
      
      // 情况2: data是对象，包含items和pagination
      if (data && typeof data === 'object' && data.items && Array.isArray(data.items)) {
        return {
          items: data.items.map((task: any) => ({
            ...task,
            id: task.id || task._id,
            assignee_name: task.assignee_name || task.assignee?.name,
            project_name: task.project_name || task.project?.name
          })),
          total: data.total || data.pagination?.total || 0,
          page: data.page || data.pagination?.page || 1,
          size: data.size || data.pagination?.size || (params?.size || 20)
        }
      }
      
      // 情况3: data直接是数组（兼容旧格式）
      if (Array.isArray(data)) {
        return {
          items: data.map((task: any) => ({
            ...task,
            id: task.id || task._id,
            assignee_name: task.assignee_name || task.assignee?.name,
            project_name: task.project_name || task.project?.name
          })),
          total: pagination?.total || data.length,
          page: pagination?.page || (params?.page || 1),
          size: pagination?.size || (params?.size || 20)
        }
      }
    }
    
    // 如果响应格式不符合预期，返回空数组并记录警告
    console.warn('Unexpected task list response format:', response.data)
    return {
      items: [],
      total: 0,
      page: params?.page || 1,
      size: params?.size || 20
    }
  })
}

/**
 * 根据项目获取任务列表（兼容旧版本）
 */
export function getTasksByProject(projectId: string, params?: TaskQueryParams) {
  return request({
    url: '/tasks/',
    method: 'get',
    params: {
      ...params,
      project_id: projectId
    }
  }).then(response => {
    // 处理统一响应格式
    if (response.data && response.data.success && response.data.data) {
      return {
        ...response,
        data: response.data.data
      }
    }
    return response
  })
}

// 任务API对象 - 统一管理所有任务相关API（向后兼容）
export const taskAPI = {
  // 获取任务列表
  getTasks: (params: any) => {
    return request({
      url: '/tasks/',
      method: 'get',
      params
    }).then(response => {
      // 处理统一响应格式
      if (response.data && response.data.success && response.data.data) {
        return {
          ...response,
          data: response.data.data
        }
      }
      return response
    })
  },

  // 获取任务详情
  getTask: (id: string) => {
    return request({
      url: `/tasks/${id}`,
      method: 'get'
    }).then(response => {
      // 处理统一响应格式
      if (response.data && response.data.success && response.data.data) {
        return {
          ...response,
          data: response.data.data
        }
      }
      return response
    })
  },

  // 创建任务
  createTask: (data: any) => {
    return request({
      url: '/tasks/create_task',
      method: 'post',
      data
    }).then(response => {
      // 处理统一响应格式
      if (response.data && response.data.success && response.data.data) {
        return {
          ...response,
          data: response.data.data
        }
      }
      return response
    })
  },

  // 更新任务
  updateTask: (id: string, data: any) => {
    return request({
      url: `/tasks/${id}`,
      method: 'put',
      data
    }).then(response => {
      // 处理统一响应格式
      if (response.data && response.data.success && response.data.data) {
        return {
          ...response,
          data: response.data.data
        }
      }
      return response
    })
  },

  // 删除任务
  deleteTask: (id: string) => {
    return request({
      url: `/tasks/${id}`,
      method: 'delete'
    }).then(response => {
      // 处理统一响应格式 - 删除操作通常只需要检查成功状态
      if (response.data && response.data.success === false) {
        throw new Error(response.data.message || '删除任务失败')
      }
      return response
    })
  }
}

export default taskAPI